

function get_content(url_read, url_write, domain_used, biov_domain, id){
	var q  = getDiseaseMQL(id, biov_domain);

	loadDataDisease(q, url_read, biov_domain, domain_used);	
}

/**
 * Generates an mql query to obtain all sub-diseases for the given disease
 * 
 * @param {string} id			The freebase id of the disease
 * @param {string} biov_domain	The bioventurist.freebase.com domain 
 */ 
function getDiseaseMQL(id, biov_domain){
 return  q  = '{"query":[{"name":null,'+
						'"type":"'+biov_domain+'bv_medical_condition",'+
						'"company_involved" : [{"*":null,"optional":true, "limit":1000, "sort":"name"}],'+		
						'"/medicine/disease/includes_diseases" : [{"*":null,"optional":true}],'+
						'"/medicine/disease/parent_disease" : [{"*":null,"optional":true}],'+
						'"/medicine/disease/stages" : [{"*":null,"optional":true}],'+
						'"/medicine/disease/survival_rates" : [{"*":null,"optional":true, "disease_stage":{"name":null, "id":null}}],'+
						'"/medicine/disease/symptoms" : [{"*":null,"optional":true}],'+
						'"/medicine/disease/treatments" : [{"*":null,"optional":true}],'+
						'"/medicine/disease/risk_factors" : [{"*":null,"optional":true}],'+
						'"id" :"'+id+'",'+
						'"guid":null'+
						'}]}';				
}

/**
 * Loads all the therapeutics that are for the given disease. 
 * 	All diseases that are included by this disease (sub-diseases) are included
 * 	when querying for the therapeutics. 
 * 
 * @param {string} mql 	The mql query for the load.
 */
function loadDataDisease(mql, url_read, biov_domain, domain_used){
		perform_freebase_read(
		url_read,
		mql,
		function (msg) {
			var disease = null;
			disease = msg.result[0];
            if (!disease) return;
            
			var disease_info = Object();
            
	        var name = disease.name;

			// Get the IDs
			disease_info.guid = disease.guid;
			disease_info.id = disease.id;
			
			// Topic info:
		    var topic_id = disease_info.id;
			var topic_domain = biov_domain+'bv_medical_condition';
			var topic_type = biov_domain+'bv_medical_condition';
            			
			// Technologies Included
	        var subDiseaseList = disease["/medicine/disease/includes_diseases"];
						
			// Read products for this disease and all sub-diseases
			var allDiseases = '"'+name+'"';
			for(var k=0;k<subDiseaseList.length;k++){
				allDiseases += ( k < subDiseaseList.length ? ', ' :"");
				allDiseases += '"'+subDiseaseList[k].name+'"';
			}
			var qThera = '{"query":[{"'+biov_domain+'bv_therapeutic/biomolecule_or_target":[],"'+biov_domain+'bv_therapeutic/indication_or_disease":[{"disease":[{"name|=":['+allDiseases+'],"id":null}],"phase_of_development":null}],"a:type":[],"brand_name":[],"a:developed_by":[{"name":null,"id":null}],"name":null,"id":null,"sales":[{"amount":null,"area":null,"optional":true,"year":null}],"stage_of_development":null,"type":"'+biov_domain+'product"}]}'; 	
			
			// customized statement to give users when the click bar data
			var info_string = "that is to treat " + name;
			
			// information on the disease
			disease_info.stages = disease['/medicine/disease/stages'];
			disease_info.survival_rates = disease['/medicine/disease/survival_rates'];

			// Symptoms
			disease_info.symptoms = disease['/medicine/disease/symptoms'];				
			var symptoms_options = {
				topic_name: name,
				topic_type : topic_type,
				topic_id: topic_id,
				current_vals: disease_info.symptoms,
				property: '/medicine/disease/symptoms',
				property_type : ['/medicine/symptom'],
			};		
			multiElement("span_symptoms", symptoms_options);

			// Risk factors
			disease_info.risk_factors = disease['/medicine/disease/risk_factors'];				
			var symptoms_options = {
				topic_name: name,
				topic_type : topic_type,
				topic_id: topic_id,
				current_vals: disease_info.risk_factors,
				property: '/medicine/disease/risk_factors',
				property_type : ['/medicine/risk_factor'],
			};		
			multiElement("span_risk_factors", symptoms_options);
			
			// Stages
			var propertyNames = ["years","rate", "disease_stage"];
			var useSuggest = [false, false, true];
			var propertyTypes = ["/type/float","/type/float", "/medicine/survival_rate/disease_stage"];
			var compoundPropertyType = "/medicine/survival_rate";
			var compoundProperty = "/medicine/disease/survival_rates";
			disease_info.survival_rates = disease["/medicine/disease/survival_rates"];
			var stages_options = {
				topicName: name,
				currentVals: disease_info.survival_rates,
				propertyNames: propertyNames,
				propertyTypes: propertyTypes,
				topic_type: topic_type,
				topic_id: topic_id,
				compoundPropertyType: compoundPropertyType,
				compoundProperty: compoundProperty,
				useSuggest: useSuggest
			};		
			compoundElement("span_survival_rates",stages_options)
			
			// Add the pipeline analysis to the report
			read_therapeutics(qThera, info_string, url_read);
			
			// Add the companies to the report
			var companies = disease["company_involved"];
			disease_info.companies = companies;
			// Companies Involved
			var companies_options = {
				topic_name: name,
				topic_type : topic_type,
				topic_id: topic_id,
				current_vals: disease_info.companies,
				property: topic_domain + '/company_involved',
				property_type : [biov_domain + 'science_or_technology_company'],
			};		
			multiElement("span_company_involved", companies_options);
			
			read_companies(companies, url_read, biov_domain, domain_used);
			
			// Disease Stages:
			var element_structure = {
				topic1_type : '["/medicine/disease_stage"]',
				topic1_html_property_name : 'Disease Stage',
				button_add_string : 'Add New Stage',
				parent_property : '/medicine/disease',
				topic2 : [
					{
						element_type : 'overview_text'
					}
				]
			}
			
			
			// For each value, return the overview text:
			var topic_domain = '/medicine/disease_stage';
			for(var a=0;a<disease_info.stages.length;a++){
				var stage_name = disease_info.stages[a].name;
				jsonp_totalblurb_freebase(domain_used, stage_name, topic_domain, 500,
					function(m){
					},
					function(m){
						// Andrey: add this blurb to the correct place in disease_info.stages
						var blurb = m.result.body;
					},
					function(m){
						var test = 0;  // If there was not overview text
						
					}
				);			
			}
			var disease_stages_options = {
				edit_blurb : "disease stages",		
				topic_name: name,
				current_vals: disease_info.stages,
				topic_type : topic_type,
				topic_id: topic_id,
				element_structure : element_structure
			};		
			mixedElement("span_stages", disease_stages_options);			
												
		},
		function(m){}
	);
}
/**
 *	Reads and loads the therapeutics for a given query.
 * 
 * @param {string} q 			The mql query for obtaining all relevent therapeutics
 * @param {string} info_string 	used when users click a given bar on the chart 
 */
function read_therapeutics(q, info_string, url_read){
	
	// Query for the therapeutics
	perform_freebase_read(
		url_read,
		q,
		function (msg2) {
	
			var therapeutics = null;
			therapeutics = msg2.result;
			if(therapeutics.length > 0){
				
				// Generate the therapeutics bar chart
				createTherapeuticsBarChartAndTable(therapeutics, info_string);		
			}
		},
		function(m){}
	);
}
/**
 * Generates a bar chart of all the therapeutics, stratified by companies (rows) and phase_of_development (cols)
 * 
 * @param {object} therapeutics	an object of all the therapeutics to be stratifiend
 * @param {string} info_string	a stock string that is desplayed to the user (amongst more customized
 * 						data) when the user clicks a bar. 
 */
function createTherapeuticsBarChartAndTable(therapeutics, info_string){
    
    // Remember all of the developers and their products
	var developers = Array();    	// the names of the developers
	var developers_stage = Array();	// the number of drugs for a given developer (row) and a given stage (column) 
	var developers_drugs = Array();	// the names of the drugs for a given developer (row) and a given stage (column)

	// Specify which phases of development to be displayed.
	var development_phases = ['Phase I Clinical Trial', 'Phase II Clinical Trial', 
							'Phase III Clinical Trial', 'On the market']
	// Colors of the bars
	var colors_vals = ['#0000FF','#0099FF','#CC6699','#CC0033'];
	
	// Initialize the data table
	var table_data = new google.visualization.DataTable();
	table_data.addColumn('string', 'Company'); //1st column is the company name
	for(var i=0;i<development_phases.length; i++){ //add columns for each phase of development
		table_data.addColumn('string', development_phases[i]);		
	}

	for (var i=0;i<therapeutics.length; i++) {
		// Get the full list of the companies that are developing the therapeutics:
		var therapeutic = therapeutics[i];
		var therapeutic_name = therapeutic.name;
		if(typeof(therapeutic.brand_name) != 'undefined'){
			if(therapeutic.brand_name.length>0){
				therapeutic_name = therapeutic.brand_name[0];
			}
		};
		var developer_list = therapeutic['a:developed_by'];
		var indications = therapeutic['/base/bioventurist/bv_therapeutic/indication_or_disease'];
		
		// Find the most developed indication
		var primary_indication_number = -1;
		for(var j=0; j<indications.length; j++){
			var phase_of_development = indications[j].phase_of_development;
			for (var k=0; k<development_phases.length; k++){
				if(phase_of_development == development_phases[k] && k>primary_indication_number){
					primary_indication_number = k;
				}
			}
		}
		
		// Record the therapeutics for each company
		for (var j=0; j<developer_list.length; j++){
			var developer = developer_list[j].name;								
			var containsDeveloper = false;
			for (var k=0; k<developers.length; k++){
				if(developer == developers[k]){
					containsDeveloper = true;	
					if(primary_indication_number > 0){
						developers_stage[k][primary_indication_number] = developers_stage[k][primary_indication_number] + 1; 
						developers_drugs[k][primary_indication_number].push(therapeutic_name); 
					}
				}
			}
			if(!containsDeveloper){
				var devIndex = developers.length; 
				developers[devIndex] = developer;
				developers_stage[devIndex] = Array();
				developers_drugs[devIndex] = Array();
				for(var a=0; a<development_phases.length; a++){
					developers_drugs[k][a] = Array();
					if(primary_indication_number > 0){	
						if(a==primary_indication_number){
							developers_stage[devIndex][a] = 1;
							developers_drugs[k][primary_indication_number].push(therapeutic_name);
						} else {
							developers_stage[devIndex][a] = 0;
						}
					}
				}				
			}
		}
								
	}	

	// Initialize the bar graph
	var barData = new google.visualization.DataTable();
	barData.addColumn('string', 'Company');
	for(var i=0;i<development_phases.length; i++){
		barData.addColumn('number', development_phases[i]);
	}

	
	var max_num_companies = 10;  // the maximum number of companies (rows) to show on the bar graph
	
	// Get the number of drugs by stage:
	var drugs_stage = Array();
	for(var i=0;i<development_phases.length; i++){
		drugs_stage[i]=0;
	}
	for(var i=0;i<developers_stage.length; i++){
		var dev_temp = developers_stage[i];
		for(var j=0;j<dev_temp.length;j++){
			drugs_stage[j] = drugs_stage[j]+dev_temp[j];
		}
	}
	
	// order the companies by the total number of products:
	var developers_total = Array();
	for(var i=0;i<developers_stage.length; i++){
		var dev_stage = developers_stage[i];
		developers_total[i] = 0;
		for(var j=0;j<dev_stage.length; j++){
			developers_total[i] = developers_total[i] + dev_stage[j];
		}
	}
	var indexes = getOrder(developers_total, developers_total.length);		
	var num_use = (indexes.length>max_num_companies ? max_num_companies : indexes.length);
	barData.addRows(num_use); // specifiy the number of rows in the bar chart
	table_data.addRows(num_use); // specifiy the number of rows in the table
	var detailed_info = Array(); // An object to hold detailed information that is used when users click a bar
	
	// Load the bar and table data 
	for (var i = 0; i < num_use; i++){
		// Abbreviate the developer's name for asthetics
		detailed_info[i] = Object();
		detailed_info[i].company = developers[indexes[i]]; 
		detailed_info[i].therapeutics = Array();
		var developer_name = developers[indexes[i]].split(" ",1);
		barData.setValue(i, 0, developer_name[0]); // add the company name to the chart
		table_data.setCell(i, 0,developers[indexes[i]]); // add the company name to the table 
		for (var j=0; j<development_phases.length; j++){
			detailed_info[i].therapeutics[j] = Object();
			detailed_info[i].therapeutics[j].num = developers_stage[indexes[i]][j];
			detailed_info[i].therapeutics[j].vals = developers_drugs[indexes[i]][j];
			var value =  (developers_stage[indexes[i]][j] > 0 ? developers_stage[indexes[i]][j] : 0.1);
			barData.setValue(i, j+1, parseFloat(value));
			table_data.setCell(i,j+1,developers_drugs[indexes[i]][j].join(', '));	
		}
	}			

	// Load the drugs_stage data into a table. 
	var bar_data_therapeutics = new google.visualization.DataTable();
	bar_data_therapeutics.addColumn('string', 'Stage of Development');
	bar_data_therapeutics.addColumn('number', 'Number of Therapeutics');	
	bar_data_therapeutics.addRows(development_phases.length); // specifiy the number of rows in the bar chart
	
	var temp_index = 0;
	for(var i=development_phases.length-1;i>=0;i--){
		bar_data_therapeutics.setValue(temp_index, 0, development_phases[i]); // add the company name to the chart
		bar_data_therapeutics.setValue(temp_index, 1, drugs_stage[i]);		
		temp_index++;
	}
 	// Set the bar chart to the html
	$("#bar_chart2_div").empty();
	var h_base = (num_use<10 ? 100 : 0);
	var chart2 = new google.visualization.ImageBarChart(document.getElementById('bar_chart2_div'));
	chart2.draw(bar_data_therapeutics, {colors:colors_vals, is3D:true, enableTooltip:false, reverseAxis:true, width:700, height:h_base+num_use*60, legend:'bottom', isStacked:true, titleX:'Number of Theapeutics'});
	
	
 	// Set the bar chart to the html
	/*
	$("#bar_chart_div").empty();
	var h_base = (num_use<10 ? 100 : 0);
	var chart = new google.visualization.ImageBarChart(document.getElementById('bar_chart_div'));
	chart.draw(barData, {colors:colors_vals, is3D:true, enableTooltip:false, reverseAxis:true, width:700, height:h_base+num_use*60, legend:'bottom', isStacked:true, titleX:'Number of Theapeutics'});
	
	// catch user click events and show them the info:	
	google.visualization.events.addListener(chart, 'select', onChartClick);
	function onChartClick(e){
	 var selection = chart.getSelection();
	 var row = selection[0].row;
	 var col = selection[0].column-1;
	 outputSelection(row,col, detailed_info, development_phases, info_string);
	}
	*/
	// Draw the table:
	var table = new google.visualization.Table(document.getElementById('table_div'));
   	table.draw(table_data, {width: 600, allowHtml: true});
	
	
	// other companies involved but not included on the list are added as a list below the bar chart:
	$("#other_companies_div").empty();
	if(indexes.length>num_use){
		var other_companies = '<h3>Other companies involved include: </h3>';
		other_companies += '<div>'
		for(var i=num_use;i<indexes.length; i++){
			other_companies += developers[indexes[i]];
			other_companies += (i<indexes.length-1 ? ', ' : '');
		}
		other_companies += '</div>'
		other_companies = $(other_companies);
		$("#other_companies_div").append(other_companies);
	}
}

// Companies Working on the Disease:
function read_companies(companies, url_read, biov_domain, domain_used){
    if (!companies) return;
	
    if(companies.length > 0) {
    	
		var linkInfo = Object();    	
		linkInfo.useLink = true;
		linkInfo.relDir = 'company';
		var htmlID = 'companies_div';
    	//createListWithHeader(companies,'Companies involved:','companies_div', 2, companyLinkInfo, true, 25);
	    var head = 'h2';
	    if(companies.length > 0) {
	  		var h = '';
  			h += '<br></br>';
	  		h+='<'+head+'><span>'+'Companies involved:'+'</span></'+head+'>';
	  		h+= '<div id="pipeline_companies"></div>';
			h = $(h)
			$("#"+htmlID+"").append(h);
			var parent_element = $("#"+htmlID+"");

			for (var j in companies) {
				var company = companies[j];
				addCompany(company, parent_element, linkInfo, url_read, biov_domain, domain_used);
//				h += (linkInfo.useLink ?'<a href="'+ create_bvr_topic_href(linkInfo.relDir, val.id) + '">' + val.name + '</a>' : '<a>'+val.name+'</a>');
//				h += ( j < companies.length-1 ? ', ' :"");
			}
		}
    	
	}
}

function addCompany(val, parent_element, linkInfo, url_read, biov_domain, domain_used){
		var id = val.id;
		var topic_name = val.name;
		// Add the header
		var h = '<hr></hr>';
		h += '<div>'+val.name+' <a href="'+ create_bvr_topic_href(linkInfo.relDir, val.id) + '">[Edit '+val.name+']</a></div>';
		h += '<br></br>'
		parent_element.append(h);
		
		var company_html_id = id.replace(/\//g,"_");
		// The overview blurb:
		parent_element.append("<h4>Edit the company's overview</h4>");
		var overview_blurb_id = company_html_id+'_overview_blurb_div';
		parent_element.append('<div id="'+overview_blurb_id+'"></div>');
		parent_element.append('<br></br>');
						
		// The company's webpage
		parent_element.append("<h4>Edit the company's webpage</h4>");
		var webpage_id = company_html_id+'_webpage_div';
		parent_element.append('<div id="'+webpage_id+'"></div>');
		parent_element.append('<br></br>');
						
		// The company's headquarters
		parent_element.append("<h4>Edit the company's headquarters</h4>");
		var headquarters_id = company_html_id+'_headquarters_div';
		parent_element.append('<div id="'+headquarters_id+'"></div>');
		parent_element.append('<br></br>');

		// The company's drug pipeline
		parent_element.append("<h4>Edit the company's drug pipeline</h4>");
		var drug_pipeline_id = company_html_id+'_drug_pipeline_div';
		parent_element.append('<div id="'+drug_pipeline_id+'"></div>');
		parent_element.append('<br></br>');
								
		var q  = '	{"query":[{'+
				'"name":null,'+
				'"board_members":[{"*":null,"optional":true}],'+
				'"companies_acquired":[{"*":null,"optional":true}],'+
				'"company_type":[{"*":null,"optional":true}],'+
				'"founded":{"*":null,"optional":true},'+
				//'"headquarters":{"*":}'
				'"headquarters":[{"optional":true,'+
					'"*":[],'+
					'"citytown" : {"optional":true,"id" : null,"name" : null},'+
					'"state_province_region":{"optional":true,"id" : null,"name" : null},'+
					'"street_address":[],'+//[{"id" : null,"name" : null}],'+
					'"postal_code":{"optional":true,"id" : null,"name" : null}'+
				'}],'+
				'"industry":[{"*":null,"limit":10,"optional":true}],'+
				'"market_capitalization":[{"*":null,"optional":true}],'+
				'"number_of_employees":[{"*":null,"optional":true}],'+
				'"operating_income":[{"*":null,"optional":true}],'+
				'"place_founded":[{"*":null,"optional":true}],'+
				'"revenue":[{"*":null,"optional":true}],'+
				'"slogan":[{"*":null,"optional":true}],'+
				'"ticker_symbol":[{"*":null,"optional":true}],'+
				'"'+biov_domain+'science_or_technology_company/area_of_expertise":[{"*":null,"optional":true}],'+
				'"'+biov_domain+'science_or_technology_company/develops_treatments_for_disease":[{"*":null,"optional":true}],'+
				'"/common/topic/webpage":[{"*":null,"optional":true}],'+
				'"'+biov_domain+'bv_therapeutic/indication_or_disease":[{'+
					'"disease":{"name":null, "id":null, "guid":null},'+
					'"optional":true,'+
					'"phase_of_development":null'+
					'}],'+
				'"'+biov_domain+'science_or_technology_company/products":[{' +
					'"*":null,' +
					'"optional":true, ' +
					'"sales":[{"*":null,"optional":true}],' +
					'"developed_by":[{"name":null,"id":null}]' +
					'}],'+
				'"thera:'+biov_domain+'science_or_technology_company/products":[{' +
					'"type":"'+biov_domain+'bv_therapeutic",'+
					'"name":null,'+
					'"id":null,'+
					'"guid":null,'+
					'"'+biov_domain+'bv_therapeutic/indication_or_disease":' +
						'[{' +
							'"guid":null,'+
							'"id":null,'+
							'"name":null,'+
							'"disease":{"name":null, "id":null, "guid":null, "optional":true},' +
							'"optional":true,' +
							'"phase_of_development":{"name":null, "id":null, "guid":null, "optional":true}' +
						'}]'+
					'}],'+
				'"guid":null,'+
				'"id" : "'+id+'",'+
				'"type":"/business/company"'+
				'}]}';
				
		perform_freebase_read(
		url_read,
		q,
		function (msg) {
		
			var company = null;
			company = msg.result[0];
	        if (!company) return;
		
			// Overview Text	
			var topic_domain = biov_domain+'science_or_technology_company';		
			//createBlurbElement(domain_used, name, topic_domain, company.id, 500, overview_blurb_id);
					
			var overviewText = new google.visualization.DataTable();
	    	overviewText.addColumn('string', '');
	    	overviewText.addColumn('string', '');
		 	overviewText.addRows(3);
			var overviewIndex = 0;
	
			var name = company.name;	
			var companyInfo = Object(); // Formatted verstion of the company information.
					
			// ID's
			companyInfo.id = company.id;
			companyInfo.guid = company.guid;
			
			// Website
			companyInfo.webpages = company["/common/topic/webpage"];
			var topic_type = biov_domain+'science_or_technology_company';	
			createWebPage_edit(webpage_id, topic_type, company.id, companyInfo.webpages)
			
			// Headquarters address
			companyInfo.headquarters = company.headquarters;			
			createHeadquarters_edit(headquarters_id, topic_name, topic_type, company.id, companyInfo.headquarters);	   	   	
						
			// Drug pipeline
			companyInfo.therapeutics = company['thera:'+biov_domain+'science_or_technology_company/products'];			
			createDrugPipeline(drug_pipeline_id, biov_domain, name, topic_type, company.id, companyInfo.therapeutics);			
			
		},
		function(m){}
	);
	var br = '<br></br><br></br>';
	parent_element.append(br);
		
}

// Need to figure out how to get this to bioventurist.js
function x(i,j,t,name, topic, freebaseDomain, table, maxlength) {
	jsonp_totalblurb_freebase(freebaseDomain, name, topic, maxlength, 
		function(m){
		},
		function(m){
			t.setCell(parseFloat(i), j, m.result.body);
   			table.draw(t, {allowHtml: true});			
		},
		function(m){} 
	);
}

	
	
function read_parentalDiseases(url_read, domain_used, name){
	var q = '{"query":[{"parent_medical_condition":[{"name":null}],"name":"'+name+'","type":"'+biov_domain+'bv_medical_condition"}]}'

	perform_freebase_read(
		url_read,
		q,
		function (msg) {
			var disease = msg.result;
	        if (!disease[0]) return;
	        parentDiseases = disease[0].parent_medical_condition;
	        if(parentDiseases.length > 0) {
	      		var h = '<br></br><h2><span>Parental Disease</span></h2>';
				for (var j in parentDiseases) {
					var dis = parentDiseases[j].name;
					h += '<a href="/disease/' + dis + '">'+dis+'</a>'
					h += ( j < parentDiseases.length-1 ? ', ' :"");
				}
				h = $(h)
				$("#parentDiseases").append(h);
			}
	        },
		function(m){}
	);
}

// Creates tables for products, stratifying them into 'On the market' and 'Development'.
//
// Draws products on the market to the table: prodMarket_div
// Draws prodcuts in development to the table: prodDev_div

function createProductsInfo(products, domain_used, biov_domain, url_read, company_name, company_html){
	
	// Separate products into productTypes
	var productObj = getProductTypes(products, "");
    
	if(productObj.therapeutics.length > 0){
		var h_TherMarket = '<h2><span>Therapeutics on the Market</span></h2>';
		h_TherMarket = $(h_TherMarket)
		$("#h_TherMarket").append(h_TherMarket); 
		var h_TherMarket = '<h2><span>Therapeutics in Development</span></h2>';
		h_TherMarket = $(h_TherMarket)
		$("#h_TherDiv").append(h_TherMarket); 
		// Need to query for therapeutic properties.
		var qThera = '{"query":[{"'+biov_domain+'bv_therapeutic/biomolecule_or_target":[],"'+biov_domain+'bv_therapeutic/indication_or_disease":[{"disease":[{"name":null, "id":null}],"optional":true,"phase_of_development":null}],"a:type":[],"brand_name":[],"developed_by":"'+company_name+'","a:developed_by":[{"name":null, "id":null}],"name":null,"id":null,"sales":[{"amount":null,"area":null,"optional":true,"year":null,"company_reporting":null}],"stage_of_development":null,"technology_involved":[],"type":"'+biov_domain+'product"}]}'; 
		//var q = '{"query":[{"developed_by":"'+name+'","name":null,"type":"/user/bioventurist/default_domain/product","brand_name":[],"a:type":[],"stage_of_development":null,"sales":[{"year":null,"amount":null,"area":null, "optional":true}]}]}';
		
		//createTherapeuticTable(productObj.therapeutics, domain_used);
		perform_freebase_read(
			url_read,
			qThera,
			function (msg2) {
				var therapeutics = null;
				therapeutics = msg2.result;
				if(therapeutics.length > 0){
					var marketCols = [0,1,2,3];
					var devCols = [0,1,2];
					var barOptions = Object();
					barOptions.salesByCompanies = false;
					barOptions.salesByProducts = true;
					var companyOptions = Object();
					companyOptions.specifyCompany = true;
					companyOptions.companyName = company_name;
					createCompanyTherapeuticsInfo(therapeutics, domain_used, biov_domain, marketCols, devCols, barOptions, false, companyOptions, company_html);		
				}
			},
			function(m){}
		);
	}
}

/* 
	Creates tables and bar charts of therapeutics.
	marketCols specify which columns are to be displayed:
	0 = Therapeutic Link
	1 = Brand Name
	2 = Developed By (Company)
	3 = 2007 Sales ($M);
	4 = 2006 Sales ($M);
	5 = 2005 Sales ($M);
	6 = Indications
	7 = Overview Text
 	8 = Large Overview Text; (always hidden, and used to allow users to expand the overview description)
	
	devCols specify which columns are to be displayed in the 'In Development' table:
	0 = Product Link
	1 = Brand Name
	2 = Developed By (Company)
	3 = Product Type (Therapeutic, diagnostic, etc.)
	4 = Overview Text
 	5 = Large Overview Text; (always hidden, and used to allow users to expand the overview description)
		NOTE: 5 and 6 are only used if the number of entries is less than 20 (due to speed)
		
	Bar Graph Options:
	barOptions.salesByCompanies
	barOptions.salesByProducts
*/
function createCompanyTherapeuticsInfo(therapeutics, domain_used, biov_domain, marketCols, devCols, barOptions, useOverviews, companyOptions, company_html_id){
    var indicationPropID = biov_domain+"bv_therapeutic/indication_or_disease";
    var biomoleculePropID = biov_domain+"bv_therapeutic/biomolecule_or_target";
    
    var therapeuticsOnTheMarket = 0;
    var therapeuticsInDevelopment = 0;
        
	var numOnMarket = 0;
	var numDev =  0;
	for (var i in therapeutics) {
    	var developmentStage = therapeutics[i].stage_of_development;
    	if(developmentStage == "On the market"){
    		numOnMarket = numOnMarket + 1;
    	} else {
    		numDev = numDev + 1;
    	}
	}
	if(numOnMarket>0){
	
	    var pMarketData = new google.visualization.DataTable();
		pMarketData.addColumn('string', 'Brand Name');
		pMarketData.addColumn('string', 'Developed By');
		pMarketData.addColumn('number', '2007 Sales ($M)');
		pMarketData.addColumn('number', '2006 Sales ($M)');
		pMarketData.addColumn('string', 'Indications / Phase of Development');
	 	pMarketData.addRows(numOnMarket);
	 	
	 	var marketTable = new google.visualization.Table(document.getElementById(company_html_id+'_theraMarket_div'));
	    var marketView = new google.visualization.DataView(pMarketData);
	 	//marketView.setColumns([0,1,2,3,4,5]);
		marketView.setColumns(marketCols);
	}
    var pDevelopmentData = new google.visualization.DataTable();
    var pDevUseOverview = (numDev < 20 ? true : false);
    	//var pDevUseOverview = true;
	pDevelopmentData.addColumn('string', 'Product');
	pDevelopmentData.addColumn('string', 'Developed By');
	pDevelopmentData.addColumn('string', 'Indications / Phase of Development');
	if(pDevUseOverview){
		pDevelopmentData.addColumn('string', 'Overview');
	 	pDevelopmentData.addColumn('string', '');
	}
 	pDevelopmentData.addRows(numDev);

	if(!pDevUseOverview){
  		var devColsTemp = Array();
  		devColsTempI = 0;
  		for(var a in devCols){
  			if(devCols[a] != 4){
  				devColsTemp[devColsTempI] = devCols[a];
  				devColsTempI = devColsTempI + 1;
  			}
  		}
  		devCols = devColsTemp;
  	}


 	var pDevTable = new google.visualization.Table(document.getElementById(company_html_id+'_theraDev_div'));
    var pDevView = new google.visualization.DataView(pDevelopmentData);
  	//var devColsToUse = (pDevUseOverview ? [0,1,2,3,4] : [0,1,2,3])
  	var devColsToUse = devCols;
	pDevView.setColumns(devColsToUse);               
    
 	var topic_domain = biov_domain+'bv_therapeutic'; 	   	

	var pMarketI = 0;
	var pDevelopmentI = 0;
	var totalSales = 0;
	
	// Record certain sales info to create bar charts:	
	var allProducts = Array();
	var allProductSales2007 = Array();
	var allProductSales2006 = Array();
	var allProductSales2005 = Array();
	
	var allDevelopers = Array();
	var allDeveloperSums2007 = Array();
	var allDeveloperSums2006 = Array();
	var allDeveloperSums2005 = Array();
				
	for (var i in therapeutics) {
		var productName = therapeutics[i].name;
		var therapeutic_id = therapeutics[i].id;
		var developmentStage = therapeutics[i].stage_of_development;
					
		var brandName = '';
		if(therapeutics[i].brand_name.length>0){
			brandName = therapeutics[i].brand_name[0];
		}
							
		var types = therapeutics[i]['a:type'];
		
		var isTherapeutic = 0;
		for (var j in types) {
			var temp = types[j];
			var temp2 = (temp == biov_domain+"bv_therapeutic") 
			if  (temp2){
				isTherapeutic = 1;
			}
		}
		var productType = 'product';

		var sales2007 = 0;
		var sales2006 = 0;
		var sales2005 = 0;
		var sales = therapeutics[i].sales;
		if(sales.length>0 && developmentStage == "On the market"){
			for (var j in sales){
							
				var useSales = false;
				if(companyOptions.specifyCompany){	
					var companyReporting = 'company_reporting';
					if(sales[j].company_reporting == companyOptions.companyName || sales[j].company_reporting == null){
						useSales = true;
					}
						
				} else {
					useSales = true;
				}
				
				if(useSales){								
					var salesYear = sales[j].year;
					var sval = (sales[j].amount)/1000000;
					if(salesYear == '2007') {
						sales2007 = (sval>sales2007 ? sval : sales2007);
						totalSales = totalSales + sales2007;
					} else if(salesYear == '2006'){
						sales2006 = (sval>sales2006 ? sval : sales2006);
					} else if(salesYear == '2005'){
						sales2005 = (sval>sales2005 ? sval : sales2005);
					}
				}
			}
		}
			
		// Get the list of developers:
		var developers = therapeutics[i]['a:developed_by'];
		var developedBy = '';
		for (var j in developers){
			var developer = developers[j];
			developedBy += '<a href="'+create_bvr_topic_href('company',developer.id)+'">' + developer.name + '</a>';
			developedBy += ( j < developers.length-1 ? ', ' :"");
			
			if(brandName.length > 0) {
				allProducts[pMarketI] = brandName;
			} else {
				allProducts[pMarketI] = productName;
			}
			allProductSales2007[pMarketI] = sales2007;
			allProductSales2006[pMarketI] = sales2006;
			allProductSales2005[pMarketI] = sales2005;
						
			var containsDeveloper = false;
			for (var k in allDevelopers){
				if(developer == allDevelopers[k]){
					containsDeveloper = true;
					var val2007 = sales2007;
					var val2006 = sales2006;
					var val2005 = sales2005;
					if(isNaN(val2007)){val2007 = 0};
					allDeveloperSums2007[k] = allDeveloperSums2007[k] + val2007;
					if(isNaN(val2006)){val2006 = 0};
					allDeveloperSums2006[k] = allDeveloperSums2006[k] + val2006;							
					if(isNaN(val2005)){val2005 = 0};
					allDeveloperSums2005[k] = allDeveloperSums2005[k] + val2005;							

				}
			}
			if(!containsDeveloper){
				var devIndex = allDevelopers.length; 
				allDevelopers[devIndex] = developer;
				var val2007 = sales2007;
				var val2006 = sales2006;
				var val2005 = sales2005;
				if(isNaN(val2007)){val2007 = 0};
				allDeveloperSums2007[devIndex] = val2007;
				if(isNaN(val2006)){val2006 = 0};
				allDeveloperSums2006[devIndex] = val2006;
				if(isNaN(val2005)){val2005 = 0};
				allDeveloperSums2005[devIndex] = val2005;
			}
		}
		
		var pName = '';
		var w = create_bvr_topic_href('therapeutic',therapeutic_id)
		if(brandName.length> 0){
			pName = '<a href="' + w + '">' + brandName + '</a>';
		} else {
			pName = '<a href="' + w + '">' + productName + '</a>';
		}							
			
		// Get the indication:
		var indications = therapeutics[i][indicationPropID];
		var indicationText = '';
		for (var j in indications){
			
			var disease = null;		
			if(indications[j].disease != null){
				if(indications[j].disease.length > 0) {
					disease = indications[j].disease[0];					
				}
			}
			var phaseOfDevelopment = '';
			if(indications[j].phase_of_development){
				if(indications[j].phase_of_development.length > 0) {
					phaseOfDevelopment += indications[j].phase_of_development;
				}
			}
			indicationText += phaseOfDevelopment+' for <a href="'+create_bvr_topic_href('disease',disease.id)+ '">' + disease.name + '</a>';
			indicationText += (j != indications.length-1 ? '; ':'');
		}	
						
		if(developmentStage == "On the market") {
			
			pMarketData.setCell(parseFloat(pMarketI), 0, brandName);
			pMarketData.setCell(parseFloat(pMarketI), 1, developedBy);
			pMarketData.setCell(parseFloat(pMarketI), 2, sales2007, sales2007);
			pMarketData.setCell(parseFloat(pMarketI), 3, sales2006, sales2006);
			pMarketData.setCell(parseFloat(pMarketI), 4, indicationText);
			
//			if(useOverviews){
//				x(pMarketI,7,8,pMarketData, marketView, productName, topic_domain, domain_used,  marketTable, 500,150);
//			}
			pMarketI = pMarketI + 1;	
			therapeuticsOnTheMarket = 1;
			
			
		} else {
			pDevelopmentData.setCell(parseFloat(pDevelopmentI), 0, productName);
			pDevelopmentData.setCell(parseFloat(pDevelopmentI), 1, developedBy);
			pDevelopmentData.setCell(parseFloat(pDevelopmentI), 2, indicationText);
			
//			if(pDevUseOverview){		
//				if(useOverviews){
//					x(pDevelopmentI,4,5,pDevelopmentData, pDevView, productName, topic_domain, domain_used,  pDevTable, 500,150);					
//				}
//			}
			pDevelopmentI = pDevelopmentI + 1;
			therapeuticsInDevelopment = 1;
				
		}
	}
	var totalPSales = 'Total sales for all '+name+' therapeutics (as caluclated from the below table) = $' +totalSales+'M.' 
	$('#'+company_html_id+'_totaltherapeuticsales_div').append(totalPSales); 
		
	// Add a bar graph outlining sales by product
	if(barOptions.salesByProducts && pMarketI > 0){
		var barDataProduct = new google.visualization.DataTable();
		barDataProduct.addColumn('string', 'Product');
		barDataProduct.addColumn('number', '2007 Sales');
		barDataProduct.addColumn('number', '2006 Sales');
		barDataProduct.addColumn('number', '2005 Sales');
		
		var numVals = allProducts.length;
		if(numVals > 16){numVals = 16};
		var indexes = getOrder(allProductSales2007, 5);
		barDataProduct.addRows(indexes.length);
		for (var k = 0; k < indexes.length; k++){
			barDataProduct.setValue(k, 0, allProducts[indexes[k]]);
			var val2007 = parseFloat(allProductSales2007[indexes[k]]);
			var val2006 = parseFloat(allProductSales2006[indexes[k]]);
			var val2005 = parseFloat(allProductSales2005[indexes[k]]);
			barDataProduct.setValue(k, 1, (isNaN(val2007) ? 0 : val2007));
			barDataProduct.setValue(k, 2, (isNaN(val2006) ? 0 : val2006));
			barDataProduct.setValue(k, 3, (isNaN(val2005) ? 0 : val2005));
		}			
		var productsChart = new google.visualization.ImageBarChart(document.getElementById(company_html_id+'_productSalesThera_div'));
		productsChart.draw(barDataProduct, {width: 650, height: 350, is3D: true, title: 'Product Sales ($M)', isStacked: false, isVertical: true});
//		$("#"+tabID).click(function () { 
//      		productsChart.draw(barDataProduct, {width: 650, height: 350, is3D: true, title: 'Product Sales ($M)'});
//    	});
			
	}
	
	if(numOnMarket){
		marketTable.draw(pMarketData, {allowHtml: true});
	}
	pDevTable.draw(pDevelopmentData, {allowHtml: true});
}


